package com.qianyitian.hope2.spider.controller;

import com.qianyitian.hope2.spider.job.StockInfoSpider;
import com.qianyitian.hope2.spider.model.Stock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@RestController
public class StockController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "stockInfoSpider")
    private StockInfoSpider stockInfoSpider = null;

//    @Scheduled(cron = "0 23 17,21,0 * * MON,TUE,WED,THU,FRI,SAT")
    //每周1-5 18:30:00 执行
    public void retrieveStockDailyData() {
        logger.info("scheduled to retrieve stock daily data");
        stockInfoSpider.run();
    }

    @GetMapping("/lastUpdateTime")
    public String getLastUpdateTime() {
        Date date = stockInfoSpider.getLastUpdateTime();
        return date.toString();
    }

    @RequestMapping("/refresh_stocks")
    @Async
    public void forceRefreshStockInfo() {
        stockInfoSpider.setCheckOutOfDate(false);
        stockInfoSpider.run();
        stockInfoSpider.setCheckOutOfDate(true);
    }

    @RequestMapping("/refresh_us")
    @Async
    public void forceRefreshUS() {
        stockInfoSpider.runUS();
    }

    @RequestMapping("/refresh_index")
    @Async
    public void forceRefreshIndex() {
        stockInfoSpider.runIndex();
    }

    @RequestMapping("/us/{code}")
    public Stock getUS(@PathVariable String code) {
        try {
            return stockInfoSpider.getUSStock(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/hk/{code}")
    public Stock getHK(@PathVariable String code) {
        try {
            return stockInfoSpider.getHKStock(code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Scheduled(cron = "04 04 04 * * SAT")
    @RequestMapping("/force_refresh_adj")
    @Async
    public void forceRefreshAdj() {
        stockInfoSpider.runStockAdjFactor();
    }

//    @Scheduled(cron = "0 18 0 * * SAT")
    //每周6 00:18:00 执行
    @RequestMapping("/refresh_stock_profile")
    @Async
    public void forceRefreshStockProfile() {
        stockInfoSpider.syncStockProfile();
    }
}
